<?php

namespace App\Http\Controllers\Api\Oauth;

use App\Core\Utils\TwHelper\Environment;
use App\Http\Controllers\Api\Controller as BaseController;
use Illuminate\Http\Request;
use App\Models\Oauth\UserModel;
use App\Models\Club\MemberModel;
use App\Services\Oauth\LoginService;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cookie;
use App\Models\Oauth\CodeModel;
use App\Models\Oauth\AuthorizeModel;
use App\Services\Oauth\Oauth2\Oauthor;
use App\Services\Oauth\Oauth2\AccessToken;
use App\Services\Oauth\User;
use App\Http\Resources\Base\UserResource;
use App\Exceptions\Response\Service\ServiceCode;
use App\Exceptions\Response\Service\ServiceException;
use App\Services\Oauth\Oauth2\App;
use App\Services\Oauth\RegistService;
use App\Services\Oauth\UserService;
use App\Core\Utils\TwHelper\CommFunction;
use App\Models\Oauth\DistrictModel;
use App\Services\Oauth\OauthorService;

/**
 * 用户登录和注册等相关api
 */
class ApiAuthController extends BaseController
{

    /**
     * 登录
     *
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'password' => 'required'
        ]);
        $userName = $request->input('mobile', '');
        $passWord = $request->input('password', '');
        //错误次数大于3次后就需要填入验证码
        $verifyCode = $request->input('verifyCode', '');
        $loginService = new LoginService($userName, $passWord, $verifyCode);
        $data = $loginService->signIn();
        //登录成功，页面刷新，会去判断登录状态，
        //eg:js( window.location.reload();)
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 快速登录
     */
    public function shortLogin(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'code' => 'required',
        ]);
        //手机号的国家码，中国：86
        $nationCode = $request->input('nationCode', 86);
        $mobile = $request->input('mobile', '');
        $code = $request->input('code', '');
        $registService = new RegistService('', $mobile, '', $code);
        //验证手机格式
        $registService->checkMobileFormat($nationCode);
        //验证短信验证码
        $registService->checkSmsCode();
        $loginService = new LoginService($mobile, '', '');
        $data = $loginService->shortSignIn($nationCode);
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 注册(PC)
     *
     * $origin 注册源；原始来源：0新用户，1通心粉社区，2企业号通讯录，3通威协同业务系统，
     *              4EBS系统，5qq，6新浪微博，7百度，8微信，9账号同步，10fbc系统，
     *              11系统导入，19管理员添加（App管理后台），21快捷登录
     */
    public function regist(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'mobile' => 'required',
            'password' => 'required',
            'code' => 'required'
        ]);
        //手机号的国家码，中国：86
        $nationCode = $request->input('nationCode', 86);
        $userName = $request->input('username', '');
        $mobile = $request->input('mobile', '');
        $passWord = $request->input('password', '');
        $code = $request->input('code', '');
        //注册源
        $origin = $request->input('origin', '0');
        $registService = new RegistService($userName, $mobile, $passWord, $code);
        //验证手机格式
        $registService->checkMobileFormat($nationCode);
        //验证手机号是否已经注册
        $registService->checkMobile();
        //验证短信验证码
        $registService->checkSmsCode();
        //验证用户名
        $registService->checkUserName();
        //验证密码格式
        $registService->checkPasswordFormat();
        $id = $registService->regist($origin, $nationCode);
        //根据注册时的ip获取到地理信息，并将省市保存到UserProfile表
        $registService->addUserProfile($id);

        //是正式环境，注册成功，将用户信息写入微信企业号通讯录
        if (Environment::isProduction()) {
            $registService->addUserInforToWeChat();
            $registService->plusUserRelateWechatUser($id);
        }
        //第3方帐号注册，建立关联关系
        $oauthorService = new OauthorService();
        $data = $oauthorService->addLoginOauth($id);
        if (!$data) {
            $data['id'] = $id;
            $data['status'] = 1;
        }
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 注册(mobile)
     *
     * $origin 注册源；原始来源：0新用户，1通心粉社区，2企业号通讯录，3通威协同业务系统，
     *              4EBS系统，5qq，6新浪微博，7百度，8微信，9账号同步，10fbc系统，
     *              11系统导入，19管理员添加（App管理后台），21快捷登录
     */
    public function registForMobile(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'mobile' => 'required',
            'password' => 'required',
        ]);
        //手机号的国家码，中国：86
        $nationCode = $request->input('nationCode', 86);
        $userName = $request->input('username', '');
        $mobile = $request->input('mobile', '');
        $passWord = $request->input('password', '');
        //注册源
        $origin = $request->input('origin', '0');
        $registService = new RegistService($userName, $mobile, $passWord, '');
        //验证手机格式
        $registService->checkMobileFormat($nationCode);
        //验证手机号是否已经注册
        $registService->checkMobile();
        //验证用户名
        $registService->checkUserName();
        //验证密码格式
        $registService->checkPasswordFormat();
        $id = $registService->regist($origin, $nationCode);

        //根据注册时的ip获取到地理信息，并将省市保存到UserProfile表
        //$registService->addUserProfile($id);

        //是正式环境，注册成功，将用户信息写入微信企业号通讯录
        if (Environment::isProduction()) {
            $registService->addUserInforToWeChat();
            $registService->plusUserRelateWechatUser($id);
        }
        //第3方帐号注册，建立关联关系
        $oauthorService = new OauthorService();
        $data = $oauthorService->addLoginOauth($id);
        if (!$data) {
            $data['id'] = $id;
            $data['status'] = 1;
        }
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 找回密码
     */
    public function getbackPassword(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required',
            'password' => 'required',
            'code' => 'required'
        ]);
        //手机号的国家码，中国：86
        $nationCode = $request->input('nationCode', 86);
        $mobile = $request->input('mobile', '');
        $passWord = $request->input('password', '');
        //短信验证码
        $code = $request->input('code', '');
        $registService = new RegistService('', $mobile, $passWord, $code);
        //验证手机格式
        $registService->checkMobileFormat($nationCode);
        $userService = new UserService();
        //验证手机号码是否注册
        $id = $userService->checkMobile($mobile);
        if (!$id) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_MOBILE_IS_NOT_USERD, '', []);
        }
        //验证短信验证码
        $registService->checkSmsCode();
        //验证密码格式
        $registService->checkPasswordFormat();
        //修改密码
        $userService->changePassword($id, $passWord);
        $data['status'] = 1;
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 检测用户名是否可以使用
     */
    public function checkUsername(Request $request)
    {
        $this->validate($request, [
            'username' => 'required'
        ]);
        $userName = $request->input('username', '');
        $registService = new RegistService($userName, '', '', '');
        //验证用户名
        $registService->checkUserName();
        $data['status'] = 1;
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 强制绑定第3方帐号
     */
    public function boundOauth(OauthorService $oauthorService)
    {
        $result = $oauthorService->boundOauth();
        return $this->response->setResponseData($result)->getResponse();
    }

    /**
     * 获取地理信息(省市县等)
     */
    public function getDistrict(Request $request, UserService $userService)
    {
        $upid = $request->input('upid', '0');
        $result = $userService->getDistrict($upid);
        return $this->response->setResponseData($result)->getResponse();
    }

    /**
     * 获取用户的类型（登录和注册后选择用户类型使用）
     */
    public function getUserTypes(UserService $userService)
    {
        $data = $userService->getUserTypes();
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 设置用户类型
     */
    public function setUserType(Request $request, UserService $userService)
    {
        $this->validate($request, [
            'userTypes' => 'required'
        ]);
        $userTypes = $request->input('userTypes', '');
        $uid = $request->input('id', '');
        if (!$uid) {
            $user = $this->identity()->getUser();
            $uid = $user['id'];
        }
        if (!$uid) {
            throw new ServiceException(ServiceCode::SERVICE_PARAM_INVALID, '', []);
        }
        if ($userService->setUserType($uid, $userTypes)) {
            $data['status'] = 1;
        }
        return $this->response->setResponseData($data)->getResponse();
    }


    /**
     * 获取国际电话区号
     */
    public function getCountryCode(Request $request, UserService $userService)
    {
        $result = $userService->getCountryCode();
        return $this->response->setResponseData($result)->getResponse();
    }

}